package com.ruoyi.common.utils.pushgateway;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.http.RestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

public class PushGatewayUtils {

    private static final Logger log = LoggerFactory.getLogger(PushGatewayUtils.class);

    public static void push(String job,String metrics){
        String url= CacheUtils.get(CacheConstants.SYS_CONFIG_KEY,"pushgateway.url",String.class);
        url = url+"/metrics/job/"+job;
        RestTemplate template = RestUtils.getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> requestEntity = new HttpEntity<>(metrics, headers);
        log.info("推送指标到pushgateway:"+url);
        ResponseEntity<String> responseEntity = template.postForEntity(url, requestEntity, String.class);
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            log.info(url+":Metrics pushed successfully to Pushgateway: ");
        } else {
            log.warn(url+":Failed to push metrics to Pushgateway. Status code: " + responseEntity.getStatusCodeValue());
        }
    }
}
